package whu.edu.assignment4.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import whu.edu.assignment4.dataobject.ReturnObj;
import whu.edu.assignment4.dataobject.User;
import whu.edu.assignment4.enums.ReturnEnums;
import whu.edu.assignment4.service.UserService;
import whu.edu.assignment4.util.ReturnUtil;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据uid找到用户
     * @param //uid
     * @return
     */
    @GetMapping("/findById")
    public ReturnObj findById(@RequestParam(value = "uid") int uid) {
        User user = userService.findById(uid);
        if(user == null) {
            return ReturnUtil.error(ReturnEnums.DataNotFound);
        }
        else {
            return ReturnUtil.success(user);
        }
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/registration")
    public ReturnObj registration(@RequestBody User user) {
        if(user == null) {
            return ReturnUtil.error(ReturnEnums.ParamError);
        }
        int result = userService.registration(user);
        if(result == -1) {
            return ReturnUtil.error(ReturnEnums.SameNameUser);
        }
        else if(result > 0) {
            return ReturnUtil.success();
        }
        else {
            return ReturnUtil.error(ReturnEnums.DataSaveError);
        }
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public ReturnObj login(@RequestBody User user) {
        if(user == null) {
            return ReturnUtil.error(ReturnEnums.ParamError);
        }
        int result = userService.login(user);
        if(result == -1) {
            return ReturnUtil.error(ReturnEnums.DataNotFound);
        }
        else if(result == 0) {
            return ReturnUtil.error(ReturnEnums.PasswordError);
        }
        else {
            return ReturnUtil.success();
        }
    }

    @GetMapping("/list")
    public ReturnObj findAll() {
        List<User> users = userService.findAll();
        if(users != null && users.size() > 0) {
            return ReturnUtil.success(users);
        }
        else {
            return ReturnUtil.error(ReturnEnums.DataNotFound);
        }
    }

    @GetMapping("/test")
    public String test() {
        return "hello world";
    }
}
